var fs = require("fs");
var String = require("../generic_class/String.js");

function MyFs(){};

//查找某个当前目录下是否存在某个文件    package.json
MyFs.isHaveFileInCurrentDir = function(path, fileName){
    var fileArr = fs.readdirSync(path);

    for(index in fileArr){
        if(fileName == fileArr[index]){
            return true;
        }
    }
    return false;
}

MyFs.isDirectory = function(path){
    try{
        var status = fs.lstatSync(path);
    } catch(e) {
        return false;
    }
    return status.isDirectory();
}

//根据上一路径是否存在 package.json判断时候是根目录
MyFs.getRoot = function(){
    var path = new String(__dirname);
    var pathNodes = path.split(new String("\\"));

    for(var i=0; i<pathNodes.length; i++){
        var needPath = "";

        for(var j=0; j<(pathNodes.length-i); j++){
            needPath = needPath + "/" + pathNodes[j].value;
        }

        needPath = needPath.substring(1, needPath.length);
        if(MyFs.isHaveFileInCurrentDir(needPath, "package.json")){
            return needPath;
        }
    }
}

//查找整个目录下是否存在某个文件


//找到某个路径下存在的所有匹配文件名的路径
MyFs.getAllMatchFilePath = function(path, fileName){
    var filePaths = MyFs.getAllFilePath(path);
    var matchFilePaths = [];

    for(var i=0; i<filePaths.length; i++){
        var filePath = new String(filePaths[i]);

        if(filePath.endsWith(new String("/" + fileName))){
            matchFilePaths.push(filePath.value);
        }
    }

    return matchFilePaths;
}

//得到某个路径下所有文件的路径
MyFs.getAllFilePath = function(path, filePaths){
    var filePaths = filePaths;
    if(!filePaths){
        filePaths = [];
    }

    var fileArr = fs.readdirSync(path);
    for(index in fileArr){
        var fileName = fileArr[index];
        var filePath = path + "/" + fileName;

        if(MyFs.isDirectory(filePath)){
            MyFs.getAllFilePath(filePath, filePaths);
        } else {
            filePaths.push(filePath);
        }
    }
    return filePaths;
}

module.exports = MyFs;